const express = require('express');
const cors = require('cors');
const { createClient } = require('@supabase/supabase-js');
const restaurantRoutes = require('./routes/restaurants');
const drawRoutes = require('./routes/draw');
const markRoutes = require('./routes/marks');
const appRoutes = require('./routes/app');

// 创建Express应用
const app = express();
const PORT = process.env.PORT || 3001;

// Supabase配置
const supabaseUrl = process.env.SUPABASE_URL || 'https://your-project.supabase.co';
const supabaseKey = process.env.SUPABASE_ANON_KEY || 'your-anon-key';
const supabase = createClient(supabaseUrl, supabaseKey);

// 中间件
app.use(cors({
  origin: ['http://localhost:8080', 'http://localhost:8081', 'http://127.0.0.1:8080', 'http://127.0.0.1:8081', 'http://localhost:5174', 'http://127.0.0.1:5174'],
  credentials: true
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 将supabase实例添加到req对象中
app.use((req, res, next) => {
  req.supabase = supabase;
  next();
});

// 路由
app.use('/api', appRoutes);
app.use('/api/restaurants', restaurantRoutes);
app.use('/api/draw', drawRoutes);
app.use('/api/marks', markRoutes);

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('Error:', err);
  res.status(err.status || 500).json({
    success: false,
    data: null,
    message: err.message || '服务器内部错误',
    error: {
      code: err.status || 500,
      type: err.name || 'InternalServerError',
      timestamp: new Date().toISOString(),
      path: req.path
    }
  });
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    data: null,
    message: '接口不存在',
    error: {
      code: 404,
      type: 'NotFound',
      timestamp: new Date().toISOString(),
      path: req.path
    }
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`🚀 服务器运行在 http://localhost:${PORT}`);
  console.log(`📚 API文档: http://localhost:${PORT}/api`);
});

module.exports = app;